define(['jquery'],function() {
    class Header {
        constructor () {
            this.load().then(() => {
                this.search()
                this.calcCartCount()
            })
        }
        load() {
            return new Promise(resolve => {
                $('header').load('/html/modules/header.html', resolve)
            }) 
        }
        search(){
            $('.search2').on('keyup', function () {
                let keyword = $(this).val() // 找到input的value
                $.getJSON(`https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${keyword}&cb=?` ,resp => {
                    $('.search1').html('')
                    resp.s.forEach(item => {
                        $(`<li>${item}</li>`).appendTo('.search1');  // 创建li放进ul里
                    })
                })
                $('.search1').on('mousedown', 'li', function (e) {
                    $('.search2').val($(e.target).html())
                    $('.search1').html('')
                })
                $('.search2').on('blur', () => {
                    $('.search1').html('')
                })
            })
        }
        // 购物车
        calcCartCount () {
            let totalCount = 0
            // 取出localStorage的数据 计算总数量
            let cart = localStorage.getItem('cart')
            if (cart) {
                cart = JSON.parse(cart)
                totalCount = cart.reduce((count, shop) => {
                    count += shop.count
                    return count
                }, 0)
            }
            $('#cartshop-num, .cart span').html(totalCount)
        }
    }
    return new Header() 
})